package com.cyl.h5.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.cyl.wechat.WechatPayService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.cyl.manager.vip.domain.entity.VipAutoRenew;
import com.cyl.manager.vip.service.IVipAutoRenewService;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.Map;
import java.time.LocalDateTime;

/**
 * VIP自动续费Controller
 *
 * @author ruoyi
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/app/vip/autoRenew")
public class H5VipAutoRenewController extends BaseController
{
    @Autowired
    private IVipAutoRenewService vipAutoRenewService;

    @Autowired
    private WechatPayService wechatPayService;

    /**
     * 查询VIP自动续费列表
     */
    @PreAuthorize("@ss.hasPermi('vip:autoRenew:list')")
    @GetMapping("/list")
    public TableDataInfo list(VipAutoRenew vipAutoRenew)
    {
        startPage();
        List<VipAutoRenew> list = vipAutoRenewService.selectVipAutoRenewList(vipAutoRenew);
        return getDataTable(list);
    }

//    /**
//     * 获取VIP自动续费详细信息
//     */
//    @PreAuthorize("@ss.hasPermi('vip:autoRenew:query')")
//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id)
//    {
//        return success(vipAutoRenewService.selectVipAutoRenewById(id));
//    }

    /**
     * 新增VIP自动续费
     */
    @PreAuthorize("@ss.hasPermi('vip:autoRenew:add')")
    @Log(title = "VIP自动续费", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@RequestBody VipAutoRenew vipAutoRenew)
    {
        int result = vipAutoRenewService.insertVipAutoRenew(vipAutoRenew);
        return result > 0 ? R.ok() : R.fail("新增失败");
    }

    /**
     * 修改VIP自动续费
     */
    @PreAuthorize("@ss.hasPermi('vip:autoRenew:edit')")
    @Log(title = "VIP自动续费", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit(@RequestBody VipAutoRenew vipAutoRenew)
    {
        int result = vipAutoRenewService.updateVipAutoRenew(vipAutoRenew);
        return result > 0 ? R.ok() : R.fail("修改失败");
    }

    /**
     * 删除VIP自动续费
     */

    @Log(title = "VIP自动续费", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public R<Void> remove(@PathVariable Long[] ids)
    {
        int result = vipAutoRenewService.deleteVipAutoRenewByIds(ids);
        return result > 0 ? R.ok() : R.fail("删除失败");
    }

    /**
     * 取消用户的自动续费
     */
    @PostMapping("/cancel/{userId}")
    public R<String> cancelAutoRenew(@PathVariable Long userId)
    {
        boolean result = vipAutoRenewService.cancelAutoRenewByUserId(userId);
        return result ? R.ok("取消自动续费成功") : R.fail("取消自动续费失败");
    }

    /**
     * 微信委托代扣签约
     */
    @PostMapping("/wechat/contract/sign/{userId}")
    public R<Map<String, Object>> signWechatContract(@PathVariable Long userId)
    {
        try {
            // 1. 查询用户的自动续费记录
            VipAutoRenew vipAutoRenew = vipAutoRenewService.selectVipAutoRenewByUserId(userId);
            if (vipAutoRenew == null) {
                return R.fail("用户未开启自动续费，请先购买VIP并开启自动续费");
            }

            // 2. 检查是否已经签约
            if (vipAutoRenew.getWechatContractId() != null &&
                vipAutoRenew.getContractStatus() != null &&
                vipAutoRenew.getContractStatus() == 1) {
                Map<String, Object> contractData = new java.util.HashMap<>();
                contractData.put("contractId", vipAutoRenew.getWechatContractId());
                contractData.put("contractCode", vipAutoRenew.getContractCode());
                contractData.put("contractStatus", vipAutoRenew.getContractStatus());
                return R.ok(contractData, "用户已完成微信委托代扣签约");
            }

            logger.info("调用微信委托代扣签约API，用户ID: {}, 原始订单号: {}", userId, vipAutoRenew.getOriginalOrderSn());

            // 3. 调用微信委托代扣签约API
            Map<String, Object> contractResult = wechatPayService.contractSign(
                userId.toString(),
                "VIP自动续费服务",
                vipAutoRenew.getOriginalOrderSn()
            );

            // 4. 处理签约结果
            if (contractResult != null && "SUCCESS".equals(contractResult.get("return_code"))) {
                // 签约成功，更新记录
                vipAutoRenew.setWechatContractId(contractResult.get("contract_id").toString());
                vipAutoRenew.setContractCode(contractResult.get("contract_code").toString());
                vipAutoRenew.setContractStatus(1); // 1表示签约成功
                vipAutoRenew.setContractTime(LocalDateTime.now());

                vipAutoRenewService.updateVipAutoRenew(vipAutoRenew);

                return R.ok(contractResult, "微信委托代扣签约成功");
            } else {
                // 签约失败
                vipAutoRenew.setContractStatus(0); // 0表示签约失败
                vipAutoRenewService.updateVipAutoRenew(vipAutoRenew);

                String errorMsg = contractResult != null ?
                    contractResult.getOrDefault("return_msg", "签约失败").toString() : "签约失败";
                return R.fail("微信委托代扣签约失败：" + errorMsg);
            }
        } catch (Exception e) {
            logger.error("微信委托代扣签约异常，用户ID：{}，错误信息：{}", userId, e.getMessage(), e);
            return R.fail("微信委托代扣签约异常：" + e.getMessage());
        }
    }

    /**
     * 查询用户的微信委托代扣签约状态
     */
    @GetMapping("/wechat/contract/status/{userId}")
    public R<Map<String, Object>> getWechatContractStatus(@PathVariable Long userId)
    {
        try {
            VipAutoRenew vipAutoRenew = vipAutoRenewService.selectVipAutoRenewByUserId(userId);
            if (vipAutoRenew == null) {
                return R.ok(null, "用户未开启自动续费");
            }

            // 构建返回数据
            Map<String, Object> contractInfo = new java.util.HashMap<>();
            contractInfo.put("hasContract", vipAutoRenew.getWechatContractId() != null);
            contractInfo.put("contractStatus", vipAutoRenew.getContractStatus());
            contractInfo.put("contractId", vipAutoRenew.getWechatContractId());
            contractInfo.put("contractCode", vipAutoRenew.getContractCode());
            contractInfo.put("contractTime", vipAutoRenew.getContractTime());

            String statusText;
            if (vipAutoRenew.getContractStatus() == null) {
                statusText = "待签约";
            } else if (vipAutoRenew.getContractStatus() == 1) {
                statusText = "已签约";
            } else {
                statusText = "签约失败";
            }
            contractInfo.put("statusText", statusText);

            return R.ok(contractInfo, "查询成功");
        } catch (Exception e) {
            logger.error("查询微信委托代扣签约状态异常，用户ID：{}，错误信息：{}", userId, e.getMessage(), e);
            return R.fail("查询签约状态异常：" + e.getMessage());
        }
    }

//    /**
//     * 查询用户的自动续费状态
//     */
//    @GetMapping("/status/{userId}")
//    public AjaxResult getAutoRenewStatus(@PathVariable Long userId)
//    {
//        VipAutoRenew vipAutoRenew = vipAutoRenewService.selectVipAutoRenewByUserId(userId);
//        if (vipAutoRenew != null && vipAutoRenew.getStatus() == 1) {
//            return success("用户已开启自动续费", vipAutoRenew);
//        } else {
//            return success("用户未开启自动续费", null);
//        }
//    }

    /**
     * 手动触发自动续费任务（仅用于测试）
     */
    @PreAuthorize("@ss.hasPermi('vip:autoRenew:test')")
    @PostMapping("/trigger")
    public R<Integer> triggerAutoRenewTask()
    {
        int processedCount = vipAutoRenewService.processAutoRenewTasks();
        return R.ok(processedCount, "手动触发自动续费任务完成，处理了 " + processedCount + " 条记录");
    }
}
